package com.xuexiang.yoyo.sql.mapper;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import androidx.annotation.NonNull;

import com.xuexiang.yoyo.constant.HesAppStatic;

import java.util.HashMap;
import java.util.Map;

public class EventCodeMapper {

    /*
    private Long id;            1
    private String code;2
    private String short_name;3
     */
    public static final String TABLE = "event_code";
    public static final String CREATE_TABLE_SQL = "CREATE TABLE " + TABLE + "(id INTEGER PRIMARY KEY AUTOINCREMENT," +
            "code TEXT ," +
            "short_name TEXT" +
            ");";


    public static void insert(String code, String shoreName) {
        ContentValues contentValues = new ContentValues();
        setContentValues(contentValues, code, shoreName);
        HesAppStatic.getmDataBaseOpenHelper().insert(TABLE, contentValues);
    }

    public static void clear() {
        HesAppStatic.getmDataBaseOpenHelper().delete(TABLE, null, null);
    }

    private static void setContentValues(ContentValues contentValues, String code, String shoreName) {
        contentValues.put("code", code);
        contentValues.put("short_name", shoreName);
    }


    public static void batchInsert(Map<String, String> eventCodeToShortName) {
        //插入之前先清空数据
        clear();
        SQLiteDatabase db = HesAppStatic.getmDataBaseOpenHelper().getWritableDatabase();
        db.beginTransaction();
        try {
            ContentValues contentValues = new ContentValues();
            for (Map.Entry<String, String> entry : eventCodeToShortName.entrySet()) {
                setContentValues(contentValues, entry.getKey(), entry.getValue());
                db.insert(TABLE, null, contentValues);
                contentValues.clear();
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();

        }
    }


    public static Map<String, String> queryAll() {
        Cursor cursor = HesAppStatic.getmDataBaseOpenHelper().query(TABLE, "");
        Map<String, String>  resultMap =getEventCodeToShortNameMap(cursor);
        cursor.close();
        return resultMap;
    }




    @NonNull
    private static Map<String, String> getEventCodeToShortNameMap(Cursor cursor) {
        Map<String, String> resultMap = new HashMap<>();
        while (cursor.moveToNext()) {
            resultMap.put(cursor.getString(1), cursor.getString(2));
        }
        return resultMap;
    }


}
